package com.lucher.mes.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lucher.mes.common.Tools;
import com.lucher.mes.dao.DepotrackinfoMapper;
import com.lucher.mes.dao.ToolplateMapper;
import com.lucher.mes.dao.ToolinoutMapper;
import com.lucher.mes.dao.ToolplateMapper;
import com.lucher.mes.dao.ToolplateinfoMapper;
import com.lucher.mes.dao.OperatorMapper;
import com.lucher.mes.dao.PrisonerMapper;
import com.lucher.mes.dao.TooldepotMapper;
import com.lucher.mes.po.Depotrackinfo;
import com.lucher.mes.po.Material;
import com.lucher.mes.po.Toolplate;
import com.lucher.mes.po.Toolinout;
import com.lucher.mes.po.Toolplate;
import com.lucher.mes.po.Toolplateinfo;
import com.lucher.mes.po.Operator;
import com.lucher.mes.po.Prisoner;
import com.lucher.mes.service.ICoderuleService;

/**
 * 用户控制层
 */
@Controller
@Scope("prototype")
@RequestMapping("/tooldepot")
@Transactional
public class TooldepotController extends BaseController {

	@Autowired
	private ToolplateMapper toolplateDao;
	@Autowired
	private ICoderuleService coderuleService;
	@Autowired
	private ToolinoutMapper toolinoutDao;
	@Autowired
	private OperatorMapper operatorDao;
	@Autowired
	private DepotrackinfoMapper depotrackinfoDao;
	@Autowired
	private PrisonerMapper prisonerDao;
	@Autowired
	private ToolplateinfoMapper toolplateinfoDao;
	
	/*
     * 特殊的instance变量
     * 注：零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：
     * 生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码。
     */
    private static byte[] lock = new byte[0];
	
	/**
	 * 查询工具库存
	 */
	@RequestMapping(value = "/findByList")
	public String findByList(Toolplate form) {
		return "tooldepot/findTooldepotList";
	}
	
	/**
	 * 查询工具库存Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findListJson")
	public Map<String, Object> findListJson(Toolplate form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
		
		Integer total = toolplateDao.findByCount(form);
		List<Toolplate> list = toolplateDao.findByList(form);
		
		Toolplateinfo toolplateinfo = new Toolplateinfo();
		
		for (Toolplate toolplate : list) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			objectMap.put("id", toolplate.getId());
			objectMap.put("toolplatecode", toolplate.getToolplatecode());
			objectMap.put("toolplatename", toolplate.getToolplatename());
			objectMap.put("rownums", toolplate.getRownums());
			objectMap.put("columnnums", toolplate.getColumnnums());
			objectMap.put("racknum", toolplate.getRacknum());
			objectMap.put("toolcode", toolplate.getToolcode());
			objectMap.put("toolname", toolplate.getToolname());
			objectMap.put("tooltype", toolplate.getTooltype());
			objectMap.put("totalnum", toolplate.getTotalnum());
			objectMap.put("leftnum", toolplate.getLeftnum());
			objectMap.put("outnum", toolplate.getOutnum());
			objectMap.put("remark", toolplate.getRemark());
			
			objectlist.add(objectMap);
		}
		
		result.put("code", "0");
		result.put("count", total);//页面总数
		result.put("data", objectlist);
		return result;
	}
    
	/**
	 * 工具入库
	 */
	@RequestMapping(value = "/indepot")
	public String indepot(Toolplate form, Model model) {
		form.setToolplate(toolplateDao.findByToolplatecode(form.getToolplatecode()));
		return "tooldepot/indepot";
	}
	
	/**
	 * 保存工具入库
	 */
	@RequestMapping(value = "/saveIndepot")
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	public Map<String,Object> saveIndepot(Toolplate form) {
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		if ("".equals(form.getToolplatecode())) {
			responseJson.put("flag", "0"); //操作失败
			responseJson.put("msg", "操作失败，请输入工具板编码");
			return responseJson;
		}
		
		Toolplate toolplate = toolplateDao.findByToolplatecode(form.getToolplatecode());
			
		if (toolplate == null) {
			responseJson.put("flag", "0");//操作失败
			responseJson.put("msg", "操作失败，此工具板不存在");
			return responseJson;
		}
		
		if(form.getInoutamount() > (toolplate.getRacknum()-toolplate.getTotalnum())){
			responseJson.put("flag", "0");//操作失败
			responseJson.put("msg", "操作失败，入库量不能大于工具版空仓位总数");
			return responseJson;
		}
		
		//库存增加
		toolplate.setTotalnum(toolplate.getTotalnum()+form.getInoutamount());
		//剩余数增加
		toolplate.setLeftnum(toolplate.getLeftnum()+form.getInoutamount());
		
		//工具入库保存
		toolplateDao.updateByPrimaryKeySelective(toolplate);
		
		responseJson.put("flag", "1");//操作成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}
	
	/**
	 * 工具领用
	 */
	@RequestMapping(value = "/outdepot")
	public String outdepot(Toolplate form,Model model) {
		form.setToolplate(toolplateDao.findByToolplatecode(form.getToolplatecode()));
		model.addAttribute("prisonerlist", prisonerDao.findPrisonerList(new Prisoner()));
		return "tooldepot/addOutdepot";
	}
	
	/**
	 * 保存工具领用
	 */
	@RequestMapping(value = "/saveOutdepot")
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	public  Map<String,Object>  saveOutdepot(Toolplate form,Toolinout toolinout) {
		Operator operator = (Operator)getSession().getAttribute("Operator");
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		//加锁
		synchronized(lock) {
			//查询工具库 存不存在此种产品
			Toolplate toolplate = toolplateDao.findByToolplatecode(form.getToolplatecode());
			if(toolplate != null){//此工具版存在
				if(toolplate.getLeftnum() > 0){//工具版有剩余工具可以领用
					//修改该工具库存量
					//已有库存量
					int leftnum = toolplate.getLeftnum();
					//本次领用量
					int inoutamount = form.getInoutamount();
					//领用量不能大于仓库剩余数
					if(leftnum-inoutamount < 0){
						responseJson.put("flag", "0"); //操作失败
						responseJson.put("msg", "操作失败，领用数量不能大于库存量！");
						return responseJson;
					}
					//更新剩余量
					toolplate.setLeftnum(leftnum-inoutamount);
					//更新借出量
					toolplate.setOutnum(toolplate.getOutnum() + inoutamount);
					
					toolplateDao.updateByPrimaryKeySelective(toolplate);
					
					//增加工具领用记录
					toolinout.setOperatorcode(operator.getLoginname());
					toolinout.setInoutamount(inoutamount);
					toolinout.setUsetime(Tools.getCurrentTime());
					toolinout.setInoutstatus("领用");
					toolinout.setDepotrackcode(toolplate.getToolplatecode());
					
					Prisoner prisoner = new Prisoner();
					prisoner.setPrisonercode(toolinout.getInoutercode());
					prisoner = prisonerDao.findPrisonerByPrisonercode(prisoner);
					if(prisoner != null){
						toolinout.setInoutername(prisoner.getPrisonername());
					}
					
					toolinoutDao.insertSelective(toolinout);
					
					responseJson.put("flag", "1"); 
					responseJson.put("msg", "操作成功");
					return responseJson;
				}else{ 
					responseJson.put("flag", "0"); //操作失败
					responseJson.put("msg", "操作失败，此工具版没有剩余工具可领用！");
					return responseJson;
				}
			}else{
				responseJson.put("flag", "0"); //操作失败
				responseJson.put("msg", "操作失败，此工具板不存在！");
				return responseJson;
			}
		}
	}
	
	
	/**
	 * 出库量
	 */
	@RequestMapping(value = "/updateDepotamountInit")
	public String updateDepotamountInit(Toolplate form,Model model) {
		form.setToolplate(toolplateDao.findByToolplatecode(form.getToolplatecode()));
		//model.addAttribute("operatorlist", operatorDao.findOperatorList(new Operator()));
		return "tooldepot/updateDepotamount";
	}
	
	/**
	 * 保存库存量的修改
	 */
	@RequestMapping(value = "/updateDepotamount")
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	public Map<String,Object>  updateDepotamount(Toolplate form) {
		Operator operator = (Operator)getSession().getAttribute("Operator");
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		//加锁
		synchronized(lock) {
			
			if ("".equals(form.getToolplatecode())) {
				responseJson.put("flag", "0"); //操作失败
				responseJson.put("msg", "操作失败，请输入工具板编码");
				return responseJson;
			}
			
			Toolplate toolplate = toolplateDao.findByToolplatecode(form.getToolplatecode());
			
			if (toolplate == null) {
				responseJson.put("flag", "0");//操作失败
				responseJson.put("msg", "操作失败，此工具板不存在");
				return responseJson;
			}
			
			if(form.getInoutamount() > toolplate.getLeftnum()){
				responseJson.put("flag", "0");//操作失败
				responseJson.put("msg", "操作失败，出库量不能大于工具剩余数");
				return responseJson;
			}
			
			//库存减少
			toolplate.setTotalnum(toolplate.getTotalnum()-form.getInoutamount());
			//剩余数减少
			toolplate.setLeftnum(toolplate.getLeftnum()-form.getInoutamount());
			
			//工具入库保存
			toolplateDao.updateByPrimaryKeySelective(toolplate);
			responseJson.put("flag", "0"); //操作失败
			responseJson.put("msg", "操作成功");
			return responseJson;
		}
	}
	
	/**
	 * 编辑产品权限初始化页面
	 */
	@RequestMapping(value = "/updateInit")
	public String updateInit(Toolplate form) {
		//form.setToolplate(tooldepotDao.selectByPrimaryKey(form.getId()));
		return "tooldepot/updateToolplate";
	}

	/**
	 * 保存编辑后产品权限
	 */
	@RequestMapping(value = "/update")
	public String update(Toolplate form) {
		//tooldepotDao.updateByPrimaryKeySelective(form);
		form.setReturninfo("修改成功");
		return updateInit(form);
	}

	/**
	 * 单个删除
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/delete")
	public Map<String,Object> delete(Toolplate form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		//删除产品
		//tooldepotDao.deleteByPrimaryKey(form.getId());
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "删除成功");
		
		return responseJson;
	}
	
	
	/**
     * 获取下拉列表框Json值
     */
	@ResponseBody //此标签表示返回的数据不是html标签的页面，而是其他某种格式的数据时（如json、xml等）使用；
	@RequestMapping(value="/getToolplateComboBoxJson")
	public List<Map<String,Object>> getToolplateComboBoxJson(Toolplate form) { 
	    List<Toolplate> tooldepotList = toolplateDao.findByList(form);
	    List<Map<String, Object>> objectComboBoxJson = new ArrayList<Map<String, Object>>();
	    //添加请选择项-默认为空，查询所有
	    //HashMap<String,Object> selectMap = new HashMap<String, Object>();
	    //selectMap.put("id", "");
	    //selectMap.put("text", "请选择");
	    //productComboBoxJson.add(selectMap);
	    
	    //封装属性结构信息
	    for(Toolplate tooldepot:tooldepotList){
	    	    HashMap<String,Object> objectMap = new HashMap<String, Object>();
	    	    objectMap.put("id", tooldepot.getId());
	    	    objectMap.put("text", tooldepot.getToolname() + "(" + tooldepot.getToolcode() + ")");
	    	    
	    	    objectComboBoxJson.add(objectMap);  
	    }  
	   return objectComboBoxJson;
	}  
	
	/**
	 * 查询工具领用界面
	 */
	@RequestMapping(value = "/findByListForUse")
	public String findByListForUse(Toolplate form) {
		return "tooldepot/findTooldepotListForUse";
	}
}
